/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain an copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ee.ioc.phon.ohos.speechutils.abilityslice;

import ee.ioc.phon.ohos.speechutils.utils.Define;
import ee.ioc.phon.ohos.speechutils.utils.DialogUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.ai.tts.TtsClient;
import ohos.ai.tts.TtsListener;
import ohos.ai.tts.TtsParams;
import ohos.ai.tts.constants.TtsEvent;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.PacMap;

import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

/**
 * 文字转语音功能类
 *
 * @since 2021-03-20
 */
public abstract class TtsBaseAbilitySlice extends AbilitySlice implements TtsShowInfoInterface {
    private static final int EVENT_MSG_INIT = 0x1000001;
    private static final int EVENT_MSG_TIME_COUNT = 0x1000002;
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "TTSAbilitySlice");
    /**
     * 是否正在进行TTS播报
     */
    protected boolean isInitItsResult;
    /**
     * 显示信息
     */
    protected String info = "";
    private int time = 0;
    private Timer timer = null;
    private TimerTask timerTask = null;

    private EventHandler handler = new EventHandler(EventRunner.current()) {
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event.eventId == EVENT_MSG_TIME_COUNT) {
                time = time + 1;
                HiLog.info(LABEL_LOG, "playTime：" + Integer.toString(time) + " s");
                info = "playTime：" + Integer.toString(time) + " s";
                showInfo(info);
            }
        }
    };

    /**
     * 监听事件
     */
    private TtsListener ttsListener = new TtsListener() {
        @Override
        public void onEvent(int eventType, PacMap pacMap) {
            HiLog.info(LABEL_LOG, "onEvent...");
            if (eventType == TtsEvent.CREATE_TTS_CLIENT_SUCCESS) {
                TtsParams ttsParams = new TtsParams();
                ttsParams.setDeviceId(UUID.randomUUID().toString());
                isInitItsResult = TtsClient.getInstance().init(ttsParams);
            }
        }

        @Override
        public void onStart(String utteranceId) {
            HiLog.info(LABEL_LOG, "onStart...");
        }

        @Override
        public void onProgress(String utteranceId, byte[] audioData, int progress) {
        }

        @Override
        public void onFinish(String utteranceId) {
            HiLog.info(LABEL_LOG, "onFinish...");
        }

        @Override
        public void onError(String errorMsg, String s1) {
            HiLog.info(LABEL_LOG, "onError...");
        }

        @Override
        public void onSpeechStart(String utteranceId) {
            HiLog.info(LABEL_LOG, "onSpeechStart...");
            initTimer();
        }


        @Override
        public void onSpeechProgressChanged(String utteranceId, int progress) {
        }

        @Override
        public void onSpeechFinish(String utteranceId) {
            // 结束计时
            HiLog.info(LABEL_LOG, "onSpeechFinish...");
            timer.cancel();
            time = 0;
            timer = null;
            timerTask = null;
        }
    };

    /**
     * 初始化timer
     */
    private void initTimer() {
        if (timer == null && timerTask == null) {
            timer = new Timer();
            timerTask = new TimerTask() {
                public void run() {
                    handler.sendEvent(EVENT_MSG_TIME_COUNT);
                }
            };
            timer.schedule(timerTask, 0, Define.YIQIAN);
        }
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(setLayout());
        initView();
        initTtsEngine();
    }

    private void initTtsEngine() {
        TtsClient.getInstance().release();
        TtsClient.getInstance().create(this, ttsListener);
    }

    /**
     * 布局
     *
     * @return 布局id
     */
    public abstract int setLayout();

    /**
     * 初始化view
     */
    public abstract void initView();

    /**
     * 开始文字转语音
     *
     * @param message 要转化的文字
     */
    protected void startTts(String message) {
        HiLog.info(LABEL_LOG, "initItsResult is true, speakText");
        if (isInitItsResult) {
            TtsClient.getInstance().stopSpeak();
            TtsClient.getInstance().speakLongText(message, null);
        } else {
            DialogUtils.showToast("初始化失败！无法播放！", getAbility());
        }
    }

    /**
     * 判断是否正在进行TTS播报。如果正在进行TTS播报，返回true；否则，返回false。
     *
     * @return 是否正在进行TTS播报
     */
    protected boolean isSpeaking() {
        boolean isFlag = false;
        if (isInitItsResult) {
            isFlag = TtsClient.getInstance().isSpeaking();
        }
        return isFlag;
    }

    /**
     * 停止播放
     */
    protected void stopSpeaking() {
        if (isInitItsResult) {
            if (isSpeaking()) {
                TtsClient.getInstance().stopSpeak();
                timer.cancel();
                time = 0;
                timer = null;
                timerTask = null;
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        TtsClient.getInstance().destroy();
    }
}
